<template>
	<view class="container">
		<!-- page=2 从修改资料页面来  page=3 从首页来 防止返回上一页跳出强制绑定 -->
		<navigationBar :backIcon="page==3?false:true"  :showHomeIcon="page==3?false:true" :titleName="'绑定手机/邮箱'"></navigationBar>
		
		<view class="content">
			<view class="logo">
				<image :lazy-load="true" src="../static/images/logo/logo.png"></image>
			</view>
			<view v-if="page==2||page==3" class="setFontColor1 setDisplayCenter tipMarginTop">
				<text>为了保证您更好地使用才能招标，请先绑定手机号</text>
			</view>
			<view class="list">

			
				<view class="list2" v-if="bindPhone==1">
					<!-- #ifdef APP-PLUS || H5 -->
					<view>
						<view class="item">
							<iconfont type="mobile"></iconfont>
							<input class="input" v-model="mobile" type="number" maxlength="11" placeholder="请输入手机号" />
						</view>
						<view class="item">
							<iconfont type="pwd"></iconfont>
							<input class="input" v-model="verify_code" placeholder-class="tip" type="number"
								maxlength="32" placeholder="请输入验证码" />
							<view class="btn-verify" @tap="getVerifyCode(1)">{{ verify_text }}</view>
						</view>

						<view class="button" hover-class="button-hover" @tap="submit(1)"><text>保存</text></view>

					</view>
					<!-- #endif -->
					
					<!-- #ifdef  MP-WEIXIN -->
					<view style="text-align: center;">
						<uni-icons type="arrowthindown"></uni-icons>
						<text style="font-size: 26rpx;">获取手机号，请点击【微信快速登录】</text>
						<uni-icons type="arrowthindown"></uni-icons>
						<button class="btn row_c" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
							<uni-icons type="weixin" color="#2ccb67"></uni-icons>微信快速登录
						</button>
					</view>
					<!-- #endif -->
				</view>

				<view class="list2" v-if="bindPhone==2">

					<view class="item">
						<iconfont type="mobile"></iconfont>
						<input class="input" v-model="user.email" maxlength="100" placeholder="请填写邮箱" />
					</view>
					<view class="item">
						<iconfont type="pwd"></iconfont>
						<input class="input" v-model="verify_code" placeholder-class="tip" type="number" maxlength="32"
							placeholder="请输入验证码" />
						<view class="btn-verify" @tap="getVerifyCode(2)">{{ verify_text }}</view>
					</view>

					<view class="submit">
						<view class="button" hover-class="button-hover" @tap="submit(2)">确定</view>

					</view>


				</view>
			</view>

		</view>
		<u-toast ref="uToast" />
		<pageLoading v-if="showPageLoading"></pageLoading>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex';
	
	import util from '@/common/util.js';
	import validator from '@/common/validator.js';
	import pageLoading from '@/components/loading/pageLoading.vue';
	import iconfont from '@/components/iconfont/iconfont.vue';
	
	
	let timing;
	export default {
		components: {
			pageLoading,
			iconfont
		},
		data() {
			return {
				mobile: '',
				verify_code: '', //验证码
				second: 0,
				tempFilePath: '',
				cropFilePath: '',
				user: {},
				showPageLoading: false,
				// 出现绑定手机号或邮箱
				bindPhone: null,
				// 记录来自哪个页面
				page: null
			};
		},
		onShow() {
			// this.$initPageTitle(); //初始化页面标题
			// let source = uni.getStorageSync('source');
			// if (source == 'login') {
			// 	uni.removeStorageSync('source');
			// 	// #ifdef H5
			// 	uni.navigateTo({
			// 		url: '/pages/user/index'
			// 	});
			// 	// #endif

			// 	// #ifndef H5
			// 	uni.switchTab({
			// 		url: '/pages/user/index'
			// 	});
			// 	// #endif
			// }
		},

		onLoad(option) {
			// #ifndef MP
			this.loadData();
			// #endif
			
			console.log(option)
			if (option.status == 2) {
				// 绑定邮箱
				this.bindPhone = 2
			} else {
				// 绑定手机
				this.bindPhone = 1
			}
			this.page = option.page

			// console.log("this.bindPhone", this.bindPhone, this.page)
		},
		// 页面销毁之前调用上个页面数据更新函数
		beforeDestroy() {
			// 用户个人信息更新
			// uni.$emit('bindVip')
			// uni.$emit('updateData')
		},
		computed: {
			verify_text() {
				if (this.second == 0) {
					return '获取验证码';
				} else {
					if (this.second < 10) {
						return '0' + this.second + '秒后获取';
					} else {
						return this.second + '秒后获取';
					}
				}
			}
		},
		onPullDownRefresh() {
			uni.showLoading({
				title: '刷新中'
			});
			// #ifndef MP
			this.loadData();
			// #endif
		},
		methods: {
			...mapMutations(['login']),
			// 手机号授权
			getPhoneNumber(e) {
				let this_ = this ;
				if (e.detail.errMsg == 'getPhoneNumber:ok') {
					uni.showLoading({
						title: "正在授权,请稍候...."
					});
					// 拿取unionid
					let unionid = uni.getStorageSync('unionid')
			
					// 拿取微信授权时存储的信息result
					let result = uni.getStorageSync('weChatResult')
			
					if (result) {
						result = JSON.parse(result)
					}
					
					console.log("result", result)
					console.log("unionid", unionid)
					let data = {
						rawData: result.rawData,
						encryptedData: e.detail.encryptedData,
						iv: e.detail.iv,
						signature: result.signature,
						unionId: unionid
					}
			
					this.$app.request({
						url: this.$baseApp.api.wechat.miniPhone,
						data: data,
						method: 'POST',
						dataType: 'json',
						success: res => {
							console.log("===================",res)
							if (res.code == 200) {
								// 将返回的信息都保存到本地中
								let userMsg = res.data
								userMsg = JSON.stringify(userMsg)
								uni.setStorageSync('userInfo', userMsg);
								this_.login(res.data);
								uni.reLaunch({
									url: '/pages/index/index'
								});
							} 
						},
						fail: err => {
							this.$alert(err.msg);
							
			
						},
						complete: res => {
							/*隐藏加载框*/
							uni.hideLoading();
						}
					});
				
			
				}
			
			
			},
			
			// 验证码发送计时器
			allTimer() {
				// 判断验证码时长
				if (this.bindPhone == 1) {
					this.second = 60;
				} else {
					this.second = 300;
				}


				this.timing = setInterval(() => {
					this.second--;
					if (this.second == 0) {
						clearInterval(this.timing);
					}
				}, 1000);
			},
			// 信息提示
			showToast(data) {
				// 判断字符长度，长度大于7，用show，小于用alter
				if (data.length >= 7) {

					this.$refs.uToast.show({
						message: data,
						type: 'success'
					})
				} else {

					this.$alert(data);
				}

			},

			/*加载数据*/
			loadData() {
				if(uni.getStorageSync('isLogin')==1)
					this.getData();
			},

			/*获取数据*/
			getData() {
				this.showPageLoading=true;
				this.$app.request({
					url: this.$baseApp.api.user.getUserInfo,
					data: {},
					method: 'GET',
					dataType: 'json',
					success: res => {
						if (res.code == 200) {
							console.log(this.user);
							this.user = res.data;
							this.mobile = this.user.mobile;
							this.cropFilePath = this.user.avatar_url;
							this.showPageLoading = false;
						} else {
							// this.$alert(res.msg);
							this.showToast(res.msg)
						}
					},
					complete: res => {
						uni.stopPullDownRefresh();
						uni.hideLoading();
					}
				});
			},

			upload() {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: res => {
						this.tempFilePath = res.tempFilePaths.shift();
					}
				});
			},
			confirm(e) {
				this.tempFilePath = '';
				this.cropFilePath = e.path;
				this.$loading('图片上传…');
				this.$app.uploadFile({
					url: this.$api.user.upload,
					filePath: e.path,
					name: 'file',
					formData: {},
					success: res => {
						console.log(res);
						console.log(res.code);
						if (res.code == 0) {
							this.user.avatar_id = res.data.id;
							this.user.avatar_url = res.data.url;
							this.cropFilePath = res.data.url;
						}
						uni.hideLoading();
					}
				});
			},
			cancel() {
				this.tempFilePath = '';
			},

			/*获取验证码*/
			getVerifyCode(num) {
				if (this.second > 0) {
					return;
				}


				if (num == 1) {
					// 获取手机验证码
					if (!validator.checkMobile(this.mobile)) {
						// this.$alert('手机号码不正确')
						return;
					}

					this.$app.request({
						url: this.$baseApp.api.common.getSms,
						data: {
							phone: this.mobile,
							type: 3
						},
						method: 'GET',
						dataType: 'json',
						success: res => {
							// this.$alert(res.msg);
							this.showToast(res.msg)
							if (res.code != 200) {
								clearInterval(this.timing)
								this.second = 0;

							} else {
								this.allTimer()
							}
						}
					});
				} else {
					// 获取邮箱验证码
					// 验证邮箱
					if (!validator.checkEmail(this.user.email)) {
						// this.$alert('邮箱不正确')
						return;
					}

					this.$app.request({
						url: this.$baseApp.api.common.getEmailSms,
						data: {
							email: this.user.email
						},
						method: 'GET',
						dataType: 'json',
						success: res => {
							console.log("这里是获取邮箱验证码", res)
							// this.$alert(res.msg);
							this.showToast(res.msg)
							if (res.code != 200) {
								clearInterval(this.timing)
								this.second = 0;

							} else {

								this.allTimer()

							}
						}
					});

				}


			},

			/*上传图片*/
			uploadPhoto() {
				uni.chooseImage({
					success: chooseImageRes => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						uni.showLoading({
							title: '上传中…'
						});
						console.log(tempFilePaths[0]);
						this.$app.uploadFile({
							url: this.$api.user.upload,
							filePath: tempFilePaths[0],
							name: 'file',
							formData: {},
							success: res => {
								console.log(res);
								console.log(res.code);
								if (res.code == 0) {
									this.user.avatar_id = res.data.id;
									this.user.avatar_url = res.data.url;
								}
								uni.hideLoading();
							}
						});
					}
				});
			},

			/*保存*/
			submit(num) {

				uni.showLoading({
					title: '提交中…'
				});
				let data = {};
				if (!validator.checkVerifyCode(this.verify_code)) {
					return;
				}
				//填入的是手机号码
				if (num == 1) {
					// 手机号验证
					if (!validator.checkMobile(this.mobile)) {
						return;
					}


					data = {
						phone: this.mobile,
						verifyCode: this.verify_code,
					};
					
					console.log("this.page",this.page)
					if(this.page==3){
						this.exitdata(data, 3)
					}else{
						this.exitdata(data, 1)
					}
					
				} else {
					// 验证邮箱验证码

					if (!validator.checkEmail(this.user.email)) {
						return;
					}

					this.$app.request({
						url: this.$baseApp.api.common.checkEmailSms,
						data: {
							email: this.user.email,
							code: this.verify_code
						},
						method: 'GET',
						dataType: 'json',
						success: res => {
							console.log("邮箱验证码校验", res)
							// 校验失败
							if (res.code != 200) {
								
								this.second = 0;
								// this.$alert(res.msg);
								this.showToast(res.msg)
								return
							} else {
								data = {
									email: this.user.email,
									showName: this.user.showName,
								};
								clearInterval(this.timing);
								this.exitdata(data, 2)
							}
						}
					});
				}
			},
			exitdata(data, num) {
				this.$app.request({
					url: this.$baseApp.api.user.updateInfo,
					data: data,
					method: 'POST',
					dataType: 'json',
					success: res => {
						if (res.code == 200) {
							// 更新用户信息
							
							this.$alert('保存成功', 'success');
							if (num == 1) {
								// 将手机号保存至本地
								uni.setStorageSync('phone', this.mobile);
								// 来自资料编辑页面2、首页3 ，返回至上一页面
								
								if (this.page) {
									uni.$emit('updateData')
									uni.navigateBack()
								}
								// 清除验证码
								this.verify_code = null
								// 清除定时器
								clearInterval(this.timing);
								this.second = 0;
								// 进入邮箱绑定页面
								this.bindPhone = 2
							}else if(num==3){
									// uni.$emit('updateData')
								// 从首页来绑定手机号，回首页去
								uni.reLaunch({
									url:'/pages/index/index'
								})
							} 
							else {
								uni.navigateBack()
							}

						} else {
							this.$alert(res.msg, 'warning');

						}

					},
					complete: res => {
						uni.hideLoading();
					}
				});
			}


		}
	};
</script>

<style lang="scss" scoped>
	.logo {
		display: flex;

		image {
			margin: 43rpx auto 0;
			height: 225rpx;
			width: 225rpx;
		}
		
	}
	.tipMarginTop{
		margin-top: 50rpx;
	}
	.list {
		margin-top: 2rpx;
		padding-left: 24rpx;
		padding-right: 24rpx;
		// border-bottom: 1rpx solid #eee;
		background: #fff;

		.list2 {
			display: flex;
			flex-direction: column;
			padding-top: 100rpx;
			padding-left: 40rpx;
			padding-right: 40rpx;

			.item {
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				align-items: center;
				height: 100rpx;
				border-bottom: 1upx solid rgba(230, 230, 230, 1) !important;

				.icon {
					color: #ababab;
					margin-right: 5rpx;
					font-size: 40rpx;
				}

				.input {
					flex: 1;
					text-align: left;
					font-size: 30rpx;
					margin-left: 16rpx;
				}
			}
		}

		.item {
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: space-between;
			min-height: 76rpx;
			border-top: 1rpx solid #eee;
			padding: 10rpx 0;

			&:first-child {
				border: 0;
			}

			.name {
				flex-grow: 0;
				flex-shrink: 0;
				display: flex;
				flex-direction: row;
				align-items: center;
				font-size: 30rpx;
				width: 200rpx;
				color: #555;

				/deep/ .icon {
					color: #0b88ff;
					margin-right: 10rpx;
				}

				/deep/ .icon-mobile-01 {
					font-size: 38rpx;
					margin-right: 5rpx;
					margin-left: -5rpx;
				}

				/deep/ .icon-policy-file {
					font-size: 30rpx;
					margin-right: 14rpx;
					margin-left: -2rpx;
					margin-top: 2rpx;
				}

				text {
					color: #555;
				}
			}

			.value {
				flex-grow: 1;
				flex-shrink: 1;
				display: flex;
				flex-direction: row;
				align-items: center;
				font-size: 30rpx;
				width: 100%;
				justify-content: flex-start;
				text-align: left;

				/deep/.icon {
					margin-left: 20rpx;
					font-size: 20rpx;
					color: #c1c4c9;
				}

				input {
					padding-right: 30rpx;
					font-size: 30rpx;
					width: 100%;
				}

				image {
					width: 60rpx;
					height: 60rpx;
					border-radius: 50%;
					margin-right: 10rpx;
				}

				text {
					margin-right: 15rpx;
					text-align: left;
					line-height: normal;
					padding: 10rpx 0 10rpx 0;
				}

				.nickname {
					font-size: 30rpx;
				}
			}

			.btn-verify {
				display: flex;
				justify-content: center;
				align-items: center;
				border: 1rpx solid #848c98;
				background: #fff;
				height: 46rpx;
				line-height: 46rpx;
				padding: 0 20rpx;
				border-radius: 55rpx;
				font-size: 26rpx;
				color: #999;
				width: 220rpx;
			}

			.tip {
				font-size: 30rpx;
				margin-right: 15rpx;
				color: grey;
			}

			.go {
				display: flex;
				flex-direction: row;
				align-items: center;
				justify-content: center;

				/deep/.icon {
					color: #dddddd;
					font-size: 20rpx;
				}
			}

			.location {
				display: flex;
				flex-direction: row;
				align-items: center;
				justify-content: center;

				/deep/.icon {
					color: grey;
				}
			}

			.drive-type {
				display: flex;
				align-items: center;

				.check-item {
					display: flex;
					align-items: center;
					margin-left: 30rpx;

					&:first-child {
						margin-left: 0;
					}

					.check-name {
						font-size: 30rpx;
						line-height: normal;
					}
				}
			}
		}

		.photo-item {
			height: 150rpx;

			image {
				width: 120rpx;
				height: 120rpx;
				border-radius: 50%;
			}
		}

		.textarea-item {
			padding-top: 10rpx;
			height: 110rpx;
			align-items: flex-start;

			.name {
				padding-top: 10rpx;
			}

			.value {
				textarea {
					padding-top: 12rpx;
					height: 100rpx;
					font-size: 30rpx;
					word-wrap: break-word;
					width: 524rpx;
					line-height: 1.5;
				}
			}
		}
	}

	.submit {
		padding: 30rpx 0 70rpx;
		background: #fff;

		.btn-text {
			display: flex;
			justify-content: center;
			margin-top: 24rpx;
			font-size: 32rpx;
			color: #8cc7b5;
		}
	}
</style>
